package com.yrh.dao.impl;

import com.yrh.dao.CommodityDao;
import com.yrh.bean.Commodity;
import com.yrh.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

//商品数据访问层实现接口
public class CommodityImpl implements CommodityDao {
   //调用JdbcTemplate
    JdbcTemplate temp=new JdbcTemplate(JDBCUtils.getDataSource());
    //商品添加
    @Override
    public int addCom(Commodity commodity) {
        //sql语句
        String sql="INSERT INTO commodity VALUES(NULL,?,?)";
        //介绍参数
        Object[] objects=new Object[]{
                commodity.getCname(),
                commodity.getCprice()
        };
        //执行操作
        int line=temp.update(sql,objects);
        return line;
    }
    //删除商品信息
    @Override
    public int deleteCom(String cname) {
        //sql语句
        String sql="DELETE FROM commodity WHERE cname=?";
        //介绍参数
        Object[] objects=new Object[]{
              cname
        };
        //执行操作
        int line=temp.update(sql,objects);
        return line;
    }
    //修改商品信息
    @Override
    public int updateCom(Commodity commodity) {
        //sql语句
        String sql="UPDATE commodity SET cprice=? WHERE cname=?";
        //介绍参数
        Object[] objects=new Object[]{
                commodity.getCprice(),
                commodity.getCname()
        };
        //执行操作
        int line=temp.update(sql,objects);
        return line;
    }
    //查询商品单价信息
    @Override
    public Commodity selectByPrice(String cname) {
        Commodity commodity=null;
        //sql语句
        String sql="SELECT distinct cprice FROM commodity WHERE cname=?";
        //介绍参数
        Object[] objects=new Object[]{
                cname
        };
        //执行操作
        List<Commodity> list = temp.query(sql, objects, new BeanPropertyRowMapper<>(Commodity.class));
        if (list.size()>0){
            for (Commodity commodity1 : list) {
                String cname1 = commodity1.getCname();
                Double cprice = commodity1.getCprice();
                commodity=new Commodity(cname1,cprice);
            }
        }
        return commodity;
    }
    //查询所有
    @Override
    public List<Commodity> selectAll() {
        String sql="SELECT * FROM commodity";
        List<Commodity> list = temp.query(sql, new BeanPropertyRowMapper<>(Commodity.class));
        return list;
    }
}
